/**
 * 读取缓存
 * @author peng-xiao-shuai
 * @date 2023-3-1
 */
export const getStorage = (name: string, type = 'object', key?: string) => {
  let data = localStorage.getItem(name) || ''

  if (type === 'object') {
    data = JSON.parse(data || '{}')
    if (key) {
      return (data as unknown as Indexes)[key]
    }
    return data
  }

  return data
}

/**
 * 格式化时间
 * @param time 时间
 * @param format 格式化字符串
 * @returns 格式化后的时间
 */
export const formatTime = (time: string | number | Date, format = 'yyyy-MM-dd HH:mm:ss') => {
  if (!time) {
    return ''
  }
  const date = new Date(time)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return format.replace('yyyy', year.toString()).replace('MM', month.toString().padStart(2, '0')).replace('dd', day.toString().padStart(2, '0')).replace('HH', hour.toString().padStart(2, '0')).replace('mm', minute.toString().padStart(2, '0')).replace('ss', second.toString().padStart(2, '0'))
}

// 校验手机号
export const validateMobile = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
    return
  } else if (!(/^(?:(?:\+|00)86)?1\d{10}$/.test(value))) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

// 校验车牌号
export const validateCarNumber = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入车牌号'))
    return
  } else if (!(/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/.test(value))) {
    callback(new Error('请输入正确的车牌号'))
  } else {
    callback()
  }
}
// 校验身份证号
export const validateIdCard = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入身份证号'))
    return
  } else if (!(/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/.test(value))) {
    callback(new Error('请输入正确的身份证号'))
  } else {
    callback()
  }
}

export function downloadFile(res: Blob, fileName: string) {
  const url = window.URL.createObjectURL(new Blob([res]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
}
